package org.objective.dal;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.sql.ResultSet;
import java.util.Iterator;
import java.util.Map;
import org.common.dynamicbean.DynamicBean;
import org.common.dynamicbean.DynamicProperty;
import org.common.utils.AnnotationUtils;
import org.objective.base.annotations.ColumnMapping;
import org.objective.base.annotations.TableMapping;

/**
 *
 * @author gus
 */
public class BeanFactory<T>
{
    private ColumnMapper  rowMapper;

    public BeanFactory(Class<T> beanInfoClass) throws Exception
    {
        if(beanInfoClass == null)
        {
            throw new IllegalArgumentException("beanInfoClass");
        }
        rowMapper = new MetaTableRowMappper(beanInfoClass);
    }

    private class MetaTableRowMappper implements ColumnMapper
    {
        private final TableMapping mapping;
        private final Map<String, PropertyDescriptor> columnMapping;

        public MetaTableRowMappper(Class beanInfoClass) throws Exception
        {
           mapping = AnnotationUtils.getAnnotation(beanInfoClass, TableMapping.class);
           columnMapping = AnnotationUtils.getFieldMappings(beanInfoClass);
        }

        @Override
        public String getTableName()
        {
            return null;//mapping.table();
        }

        @Override
        public String getColumnName(String field)
        {
            return columnMapping.get(field).getName();
        }

        @Override
        public String primaryColumnName()
        {
            return null;
        }

    }

    public BeanFactory(ColumnMapper rowMapper)
    {
        this.rowMapper = rowMapper;
    }


    public ColumnMapper getRowMapper()
    {
        return rowMapper;
    }

 
    public DynamicBean makeTemplate() throws Exception
    {
        return null;
    }

    public DynamicBean makeFromResultSet(ResultSet rs, DynamicBean template) throws Exception
    {
        DynamicBean bean = (DynamicBean) template.clone();
        Iterator<String> nameIter = template.nameIterator();
        while (nameIter.hasNext())
        {
            String propertyName = nameIter.next();
            bean.setValue(propertyName, rs.getObject(propertyName));
        }
        return bean;
    }

  
}
